package br.com.rumus.dao.seguranca;

import java.util.List;

import javax.persistence.Query;
import br.com.rumus.dao.DAOGenerico;
import br.com.rumus.dominio.seguranca.Papel;

public class PapelDAO extends DAOGenerico<Papel, Long> {
	
	@SuppressWarnings("unchecked")
	public List<Papel> pesquisar( Papel papel, int registro, int quantidade ){
		StringBuilder JPQL = new StringBuilder( "select p from Papel p where ( p.descricao like :descricao or :descricao is null ) and ( p.nome like :nome or :nome is null )" );
		Query query = getEntityManager().createQuery(JPQL.toString());
		query.setParameter("descricao", (papel!=null&&papel.getDescricao()!=null&&!papel.getDescricao().equals(""))?papel.getDescricao():null);
		query.setParameter("nome", (papel!=null&&papel.getNome()!=null&&!papel.getNome().equals(""))?papel.getNome():null);
		query.setFirstResult(registro);
		query.setMaxResults(quantidade);
		return query.getResultList();
	}

	public int pesquisar( Papel papel ){
		StringBuilder JPQL = new StringBuilder( "select count(*) from Papel p where ( p.descricao like :descricao or :descricao is null ) and ( p.nome like :nome or :nome is null )" );
		Query query = getEntityManager().createQuery(JPQL.toString());
		query.setParameter("descricao",(papel!=null&&papel.getDescricao()!=null&&!papel.getDescricao().equals(""))?papel.getDescricao():null);
		query.setParameter("nome",(papel!=null&&papel.getNome()!=null&&!papel.getNome().equals(""))?papel.getNome():null);
        Number registros = null;
        registros = (Number) query.getSingleResult();
        return registros == null ? 0 : registros.intValue();
	}

	public boolean existeNome(String nome){
		StringBuilder JPQL = new StringBuilder( "select count(*) from Papel p where p.nome=:nome" );
		Query query = getEntityManager().createQuery(JPQL.toString());
		query.setParameter("nome", nome);
		Number registros = null;
        registros = (Number) query.getSingleResult();
		return (registros.intValue()>0);
	}
	
	public boolean existeDescricao(String descricao){
		StringBuilder JPQL = new StringBuilder( "select count(*) from Papel p where p.descricao=:descricao" );
		Query query = getEntityManager().createQuery(JPQL.toString());
		query.setParameter("descricao", descricao);
		Number registros = null;
        registros = (Number) query.getSingleResult();
		return (registros.intValue()>0);
	}
	
	public boolean vinculoPapel(Papel papel){
		StringBuilder JPQL = new StringBuilder( "select count(*) from Perfil p where :papel MEMBER OF p.papeis" );
		Query query = getEntityManager().createQuery(JPQL.toString());
		query.setParameter("papel", papel);
		Number registros = null;
        registros = (Number) query.getSingleResult();
		return (registros.intValue()>0);
	}
	
}